import React from 'react';
import { Modal, Row, Col, Select, message, Button, Collapse } from 'antd';
import Editor from '@/utils/Editor';
import JsonAnswer from '@/pages/KnowledgeManagement/Overview/EditingKnowledge/jsonAnswer';
import jsonDataUtils from '@/utils/jsonDataUtils';
import UserSession from "@/UserSession";

class AddAnswer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      robotName: '',
      robotId: '',
      slotValues: [],
      userTagIdList: [],
      referAnswer: {
        isRefer: false,
      },
      content: '',
      answerType: 'richText',
      jsonContent: JSON.parse(JSON.stringify(jsonDataUtils.initJsonData))
    }
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

  initModal = (robotName, robotId) => {
    this.setState({ visible: true, robotName, robotId })
  }

  cancelModal = () => {
    this.setState({
      visible: false,
      robotName: '',
      robotId: '',
      slotValues: [],
      userTagIdList: [],
      referAnswer: {
        isRefer: false,
        // referInfo:{},
      },
      content: ''
    })
  }

  /**
   * 选择词槽
   * @returns {*}
   */
  changeSlot = (values, id, slotName, keyName) => {
    let { slotValues } = this.state;
    //判断当前词槽是否选择过 没有则添加 有则修改
    const slotIds = slotValues.map(item => item.id)
    if (slotIds.indexOf(id) === -1) {
      slotValues.push({ id, slotName, keyName, values });
    } else {
      if (values.length === 0) {//词槽值全部删除，则去掉该词槽
        const newSlotValues = slotValues.filter(slot => slot.id != id);
        slotValues = newSlotValues;
      } else {
        for (let item of slotValues) {
          if (item.id === id) {
            item.values = values;
          }
        }
      }
    };
    this.setState({ slotValues });
  }

  /**
   * 选择标签
   */
   changeTag = (values, option) => {
    let userTagIdList = option.map(tag => {
      let item = tag.props.item;
      return { id: item.id, tagName: item.tagName };
    });
    this.setState({ userTagIdList });
   }

  /**
   * 选择引用答案
   */
  changeContentFromRefer = (row) => {
    this.setState({
      referAnswer: {
        isRefer: true,
        // referInfo:row,
        content: row.answer,
        contentId: row.id,
        question: row.question
      },
      content: row.answer,
      /* 若之前的答案类型为json 则引用答案之后需要将类型修改为富文本 防止取消引用后保存content会被jsonContent覆盖 */
      answerType: 'richText'
    })
  }

  /**
   * 取消引用
   */
  dereferenceAnswer = () => {
    this.setState({
      referAnswer: {
        isRefer: false,
        contentId: undefined,
        question: undefined,
        // referInfo:{},
      }
    })
  }

  /**
   * 保存答案
   * @returns {*}
   */
  saveAnswer = () => {
    const { slotValues, userTagIdList, robotId, referAnswer, content, answerType, jsonContent } = this.state;
    const { slotDetailArr } = this.props;
    const con = `answer`;
    let contentResult = '';
    let answer = {
      isDefault: false,
      slotValues,
      userTagIdList,
    };
    if (referAnswer.isRefer) {
      contentResult = content;
      answer.isRefer = true;
      answer.contentId = referAnswer.contentId;
      answer.question = referAnswer.question;
      // answer.referInfo = referAnswer.referInfo;
    } else {
      if (con && this.refs[con]) {
        contentResult = this.refs[con].getUeditorContent();
      } else {
        contentResult = '';
      }
    };

    //判断json合法性
    const jsonResult = jsonDataUtils.judgeJson(jsonContent);
    if (answerType === 'json' && !jsonResult.flag) {
      message.error(jsonResult.msg)
      return false
    };

    if (answerType === 'json' && jsonResult.flag) {
      contentResult = JSON.stringify(jsonContent);
      answer.answerType = 'json';
      answer.jsonContent = jsonContent;
      answer.jsonResult = jsonResult;
    };

    answer.content = contentResult;
    if (slotDetailArr && slotDetailArr.length > 0) {
      let arr = slotDetailArr.filter(item => item.isEnum);
      let arrSlot = arr.map(item => item.id);
      let slotValuesCheck = !slotValues || slotValues.length === 0 ? [] : slotValues.filter(item => item.values.length > 0);
      if (arr.length > 0 && (slotValues && slotValues.length > 0 && slotValuesCheck.length < slotValues.length)) {
        message.error('词槽答案词槽值不能为空，请选择词槽');
        return false;
      };
    } else {
      if (!UserSession.isAdmin() && (!userTagIdList || userTagIdList.length === 0)) {
        message.error('用户标签不能为空，请选择标签');
        return false;
      };
    };
    if (!contentResult) {
      message.error('请添加答案');
      return false;
    };
    this.props.addSlotAnswer(answer, robotId);
    this.cancelModal();
  }

  /* 设置答案为json */
  toJsonAddAnswer = () => {
    //1.获取当前编辑框内的富文本内容，保存至content中，为了json编辑时返回富文本编辑后还能显示之前的内容
    //2.修改当前答案的类型为json
    const content = this.refs['answer'].getUeditorContent();

    this.setState({ content, answerType: 'json' });
  }

  /* 修改json答案 */
  updateJsonAnswer = (option, data) => {
    switch (option) {
      case 'backToRich':
        this.setState({ answerType: 'richText' });
        break;
      case 'update':
        this.setState({ jsonContent: data });
        break;
    }
  }

  render() {
    const { visible, robotName, slotValues, referAnswer, content, answerType, jsonContent } = this.state;
    const { slotDetailArr, userTagList } = this.props;
    const referAnswerHeader = referQuestion => (
      <span>引用自答案库：<a>{referQuestion}</a></span>
    )
    const referAnswerExtra = UserSession.isSystemKnowledge() ? null : (
      <span>
        <span style={{ marginRight: 5, color: '#11cbff' }} onClick={() => this.props.openReferAnswer('slotAdd')}>更换</span>
        <span style={{ color: '#11cbff' }} onClick={this.dereferenceAnswer}>取消引用</span>
      </span>
    )
    return (
      <Modal
        visible={visible}
        title={'添加/编辑答案'}
        onCancel={this.cancelModal}
        width={800}
        onOk={this.saveAnswer}
        destroyOnClose
      >
        <Row>
          <Col span={3}>适用于：</Col>
          <Col span={21}>{robotName}</Col>
        </Row>
        {slotDetailArr && slotDetailArr.length > 0 ? (
          <Row style={{ marginTop: 10 }}>
            <Col span={3}>词槽条件：</Col>
            <Col span={21}>
              {
                slotDetailArr.map((slot, index) => {
                  return (
                    <Row key={index} style={{ marginTop: index === 0 ? 0 : 10 }}>
                      <Col span={4}>
                        &lt;{slot.name}&gt; =
                      </Col>
                      <Col span={20}>
                        {
                          slot.isEnum ? (
                            <Select mode="multiple" style={{ width: '100%' }} onChange={(values) => this.changeSlot(values, slot.id, slot.name, slot.keyName)}>
                              {
                                slot.items.map((item, itemIndex) => {
                                  return (
                                    <Select.Option value={item.word} key={item.id}>{item.word}</Select.Option>
                                  )
                                })
                              }
                            </Select>
                          ) : '词槽值不可枚举，不支持设置条件'
                        }
                      </Col>
                    </Row>
                  )
                })
              }
            </Col>
          </Row>
        ) : null}
        {!UserSession.isAdmin() ? (
          <Row style={{ marginTop: 10 }}>
            <Col span={3}></Col>
            <Col span={21}>
              <Row style={{ marginTop: 10 }}>
                <Col span={4}>
                  &lt;{'用户标签'}&gt; =
                </Col>
                <Col span={20}>
                  <Select mode="multiple" style={{ width: '100%' }} onChange={(values, option) => this.changeTag(values, option)}>
                    {
                      userTagList.map((item, itemIndex) => {
                        return (
                          <Select.Option value={item.tagName} key={item.id} item={item}>{item.tagName}</Select.Option>
                        )
                      })
                    }
                  </Select>
                </Col>
              </Row>
            </Col>
          </Row>
        ) : null}
        {UserSession.isSystemDataKnowledge() ? null : (
          <>
            {!referAnswer.question ? (
              <Row style={{ marginTop: 10 }}>
                <Col style={{ textAlign: 'right' }}>
                  <Button style={{ backgroundColor: '#E5ECF4' }} onClick={() => this.props.openReferAnswer('slotAdd')}>引用答案</Button>
                </Col>
              </Row>
            ) : null}
          </>
        )}
        <Row style={{ marginTop: 10 }}>
          <Col span={3}>答案：</Col>
          <Col span={21}>
            <div>
              {
                referAnswer.question ? (
                  <Collapse expandIconPosition={'right'} defaultActiveKey={referAnswer.id}>
                    <Collapse.Panel header={referAnswerHeader(referAnswer.question)} extra={referAnswerExtra} key={referAnswer.id}>
                      <div dangerouslySetInnerHTML={{ __html: content }} />
                    </Collapse.Panel>
                  </Collapse>
                ) : (
                  answerType && answerType === 'json' ? (
                    <JsonAnswer
                      jsonContent={jsonContent}
                      updateJsonAnswer={this.updateJsonAnswer}
                      typeOfAnswer={'addAnswer'}
                    />
                  ) : (
                    <Editor
                      content={content}
                      name={`answer`}
                      id={`answer`}
                      ref={`answer`}
                      toJson={this.toJsonAddAnswer}
                    />
                  )
                )
              }
            </div>
          </Col>
        </Row>
      </Modal>
    );
  }
}

export default AddAnswer;
